package cn.gson.school.controller.xitong;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.school.dao.ImagesDao;
import cn.gson.school.dao.xitong.DeptSerchDao;
import cn.gson.school.dao.xitong.RoleSerchDao;
import cn.gson.school.dao.xitong.UserDao;
import cn.gson.school.dao.xitong.UserInfoDao;
import cn.gson.school.entity.xitong.DeptEntity;
import cn.gson.school.entity.xitong.RoleEntity;
import cn.gson.school.entity.xitong.UserEntity;
import cn.gson.school.entity.xitong.UserInfoEntity;
import cn.gson.school.mappers.xitong.EmpMapper;
import cn.gson.school.service.xitong.EmpService;
import lombok.extern.log4j.Log4j;

@Log4j
@Controller
@RequestMapping("/emp")
public class EmpController {
	@Autowired
	private EmpMapper empMapper;

	@Autowired
	private UserInfoDao empDao;

	@SuppressWarnings("unused")
	@Autowired
	private EmpService empService;

	@Autowired
	private UserDao userDao;
	@Autowired
	private DeptSerchDao deptDao;

	/**
	 * 获取表单的信息
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("xt-add-emp")
	public String from(Model model) {
		List<DeptEntity> deptlist = empMapper.deptList();
		List<RoleEntity> rolelist = empMapper.roleList();
		model.addAttribute("deptlist", deptlist);
		model.addAttribute("rolelist", rolelist);
		return "xitong/xt-add-emp";

	}

	/**
	 * 查询
	 * 
	 * @param emp
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> index(UserInfoEntity emp, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<UserInfoEntity> pageData = empMapper.selectAll(emp);
		PageInfo<UserInfoEntity> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	@SuppressWarnings("unused")
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid UserEntity user, @Valid UserInfoEntity emps,
			@RequestParam(name = "roleName") Long roleId, @RequestParam(name = "deptName") Long deptInfo,
			HttpServletRequest request, BindingResult br) {
		System.out.println("user:" + user);
		System.out.println("emp:" + emps);
		System.out.println("deptId:" + deptInfo);
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("error", br.getFieldErrors());
		} else {

			String userInfoId = request.getParameter("userInfoId");
			String userAccount = request.getParameter("userAccount");
			String userName = request.getParameter("userName");
			String userAge = request.getParameter("userAge");
			String userSex = request.getParameter("userSex");
			String userTel = request.getParameter("userTel");
			if (userTel != null || !"".equals(userTel)) {
				if (userTel.length() != 11) {
					obj.put("message", "亲！手机号码必须是11位!");
				}
			}
			if (userAccount != null || "".equals(userAccount)) {
				if (userAccount != null) {
					obj.put("message", "亲！用户账号不能为空！！");
				}
			}

			if (userInfoId == null || "".equals(userInfoId)) {
				// 添加角色
				RoleEntity role = new RoleEntity();
				role.setRoleId(roleId);
				List<RoleEntity> roles = new ArrayList<>();
				roles.add(role);
				user.setRoles(roles); // 时间
				user.setUserPass(DigestUtils.md5Hex("123456789"));
				user.setRegistTime(new Date());
				userDao.save(user);
			} else {
				// 编辑
				emps = empDao.findOne(emps.getUserInfoId());
				emps.setUserInfoId(emps.getUserInfoId());
			}
			// 添加部门
			DeptEntity dept = new DeptEntity();
			dept.setDeptId(deptInfo);
			emps.setDept(dept);
			emps.setHiredate(new Date());
			emps.setDelete(1);
			user.setDelete(1);
			user.setImagesId(Long.valueOf(1+""));
			user.setEnable(true);
			user = userDao.findByUserAccount(userAccount);
			System.out.println("zzzzz" + userDao.findByUserAccount(userAccount));
			emps.setUserId(user);
			UserInfoEntity emp1 = empDao.save(emps);
			obj.put("success", true);

		}
		return obj;
	}

	/**
	 * 获取修改表单的信息
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("xt-edit-emp/{id}")
	public String from1(@PathVariable(name = "id") Long id, Model model) {
		if (id != null) {
			System.out.println("编辑编号是：" + id);
			UserInfoEntity emp = empDao.findOne(id);
			System.out.println("用户信息：" + emp);
			DeptEntity dept = deptDao.findOne(emp.getDept().getDeptId());
			System.out.println("用户部门信息：" + dept);
			if (emp != null) {
				model.addAttribute("emp", emp);
				model.addAttribute("dept", dept);
			}
		}
		List<DeptEntity> deptlist = empMapper.deptList();
		List<RoleEntity> rolelist = empMapper.roleList();
		model.addAttribute("deptlist", deptlist);
		model.addAttribute("rolelist", rolelist);
		return "xitong/xt-edit-emp";

	}

	/**
	 * 编辑
	 */

	@PostMapping("edit")
	@ResponseBody
	@Transactional
	public JSONObject edit(@Valid UserInfoEntity emps, BindingResult br) {
		System.out.println("ssisisis");
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("error", br.getFieldErrors());
		}

		UserInfoEntity emp1 = empDao.findOne(emps.getUserInfoId());
		if (emp1.getUserInfoId() == null) {
			if (emp1.getUserTel() == null) {
				obj.put("message", "联系电话不能为空！");
				return obj;
			}
		} else {
			if (emps.getUserTel() != null) {
				emp1.setUserTel(emps.getUserTel());
			} else {
				UserInfoEntity r = empDao.findOne(emps.getUserInfoId());
				emp1.setUserTel(r.getUserTel());
			}
			if (emps.getUserName() != null) {
				emp1.setUserName(emps.getUserName());
			} else {
				UserInfoEntity r = empDao.findOne(emps.getUserInfoId());
				emp1.setUserName(r.getUserName());
			}
			if (emps.getHiredate() != null) {
				emp1.setHiredate(emps.getHiredate());
			} else {
				UserInfoEntity r = empDao.findOne(emps.getUserInfoId());
				emp1.setHiredate(r.getHiredate());
			}
			if (emps.getUserSex() != null) {
				emp1.setUserSex(emps.getUserSex());
			} else {
				UserInfoEntity r = empDao.findOne(emps.getUserInfoId());
				emp1.setUserSex(r.getUserSex());
			}
			if (emps.getDept() != null) {
				emp1.setDept(emps.getDept());
			} else {
				UserInfoEntity r = empDao.findOne(emps.getUserInfoId());
				emp1.setDept(r.getDept());
			}
			if (emps.getUserAge() != null) {
				emp1.setUserAge(emps.getUserAge());
			} else {
				UserInfoEntity r = empDao.findOne(emps.getUserInfoId());
				emp1.setUserAge(r.getUserAge());
				
			}
		}
		empDao.save(emp1);
		obj.put("success", true);
		return obj;

	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public Map<String, Object> delete(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		UserInfoEntity emp;
		if (id != null && (emp = empDao.findOne(id)) != null) {
			emp.setDelete(0);
			obj.put("success", true);
		} else {
			obj.put("message", "改员工不存在！");
		}
		return obj;
	}
}
